package com.ruoyi.wms.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.wms.mapper.WmsMaterialCategoryMapper;
import com.ruoyi.wms.domain.WmsMaterialCategory;
import com.ruoyi.wms.service.IWmsMaterialCategoryService;
import com.ruoyi.common.core.text.Convert;

/**
 * 物料类别树Service业务层处理
 * 
 * @author 杨懿
 * @date 2023-11-27
 */
@Service
public class WmsMaterialCategoryServiceImpl implements IWmsMaterialCategoryService 
{
    @Autowired
    private WmsMaterialCategoryMapper wmsMaterialCategoryMapper;

    /**
     * 查询物料类别树
     * 
     * @param deptId 物料类别树主键
     * @return 物料类别树
     */
    @Override
    public WmsMaterialCategory selectWmsMaterialCategoryByDeptId(Long deptId)
    {
        return wmsMaterialCategoryMapper.selectWmsMaterialCategoryByDeptId(deptId);
    }

    /**
     * 查询物料类别树列表
     * 
     * @param wmsMaterialCategory 物料类别树
     * @return 物料类别树
     */
    @Override
    public List<WmsMaterialCategory> selectWmsMaterialCategoryList(WmsMaterialCategory wmsMaterialCategory)
    {
        return wmsMaterialCategoryMapper.selectWmsMaterialCategoryList(wmsMaterialCategory);
    }

    /**
     * 新增物料类别树
     * 
     * @param wmsMaterialCategory 物料类别树
     * @return 结果
     */
    @Override
    public int insertWmsMaterialCategory(WmsMaterialCategory wmsMaterialCategory)
    {
        WmsMaterialCategory info = wmsMaterialCategoryMapper.selectWmsMaterialCategoryByDeptId(wmsMaterialCategory.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        wmsMaterialCategory.setAncestors(info.getAncestors() + "," + wmsMaterialCategory.getParentId());
        wmsMaterialCategory.setCreateTime(DateUtils.getNowDate());
        return wmsMaterialCategoryMapper.insertWmsMaterialCategory(wmsMaterialCategory);
    }

    /**
     * 修改物料类别树
     * 
     * @param dept 物料类别树
     * @return 结果
     */
    @Override
    public int updateWmsMaterialCategory(WmsMaterialCategory dept)
    {
        WmsMaterialCategory newParentDept = wmsMaterialCategoryMapper.selectWmsMaterialCategoryByDeptId(dept.getParentId());
        WmsMaterialCategory oldDept = wmsMaterialCategoryMapper.selectWmsMaterialCategoryByDeptId(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = wmsMaterialCategoryMapper.updateWmsMaterialCategory(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
        /*wmsMaterialCategory.setUpdateTime(DateUtils.getNowDate());
        return wmsMaterialCategoryMapper.updateWmsMaterialCategory(wmsMaterialCategory);*/
    }
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {
        List<WmsMaterialCategory> children = wmsMaterialCategoryMapper.selectChildrenDeptById(deptId);
        for (WmsMaterialCategory child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            wmsMaterialCategoryMapper.updateDeptChildren(children);
        }
    }
    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(WmsMaterialCategory dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        wmsMaterialCategoryMapper.updateDeptStatusNormal(deptIds);
    }
    /**
     * 批量删除物料类别树
     * 
     * @param deptIds 需要删除的物料类别树主键
     * @return 结果
     */
    @Override
    public int deleteWmsMaterialCategoryByDeptIds(String deptIds)
    {
        return wmsMaterialCategoryMapper.deleteWmsMaterialCategoryByDeptIds(Convert.toStrArray(deptIds));
    }

    /**
     * 删除物料类别树信息
     * 
     * @param deptId 物料类别树主键
     * @return 结果
     */
    @Override
    public int deleteWmsMaterialCategoryByDeptId(Long deptId)
    {
        return wmsMaterialCategoryMapper.deleteWmsMaterialCategoryByDeptId(deptId);
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTree(WmsMaterialCategory dept)
    {
        List<WmsMaterialCategory> deptList = wmsMaterialCategoryMapper.selectWmsMaterialCategoryList(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 查询部门管理树（排除下级）
     *
     * @param deptId 部门ID
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTreeExcludeChild(WmsMaterialCategory dept)
    {
        Long excludeId = dept.getExcludeId();
        List<WmsMaterialCategory> deptList = wmsMaterialCategoryMapper.selectWmsMaterialCategoryList(dept);
        Iterator<WmsMaterialCategory> it = deptList.iterator();
        while (it.hasNext())
        {
            WmsMaterialCategory d = (WmsMaterialCategory) it.next();
            if (d.getDeptId().intValue() == excludeId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), excludeId + ""))
            {
                it.remove();
            }
        }
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }



    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<WmsMaterialCategory> deptList)
    {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<WmsMaterialCategory> deptList, List<String> roleDeptList)
    {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (WmsMaterialCategory dept : deptList)
        {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()))
            {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setpId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                if (isCheck)
                {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }
    @Override
    public int selectDeptCount(Long parentId)
    {
        WmsMaterialCategory dept = new WmsMaterialCategory();
        dept.setParentId(parentId);
        return wmsMaterialCategoryMapper.selectDeptCount(dept);
    }
}
